package com.liyuxiang.service.impl;

import com.liyuxiang.domain.LoginUser;
import com.liyuxiang.domain.ResponseResult;
import com.liyuxiang.pojo.entity.User;
import com.liyuxiang.pojo.vo.UserVo;
import com.liyuxiang.service.LoginService;
import com.liyuxiang.utils.JwtUtil;
import com.liyuxiang.utils.RedisCache;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user, HttpServletResponse response) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //AuthenticationManager authentication进行用户认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        System.out.println("到这里了");
        //TODO  它在这里是怎么调用UserDeatilsServiceImpl的？
        //如果认证没通过抛出异常
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long userId = loginUser.getUser().getId();
        String token = JwtUtil.createJWT(userId.toString());
        response.setHeader("token",token);
        //如果查询不为空代表有这个用户    TODO 接下来比较密码
//        passwordEncoder.encode()
        //如果没有查询到用户就跑出异常
//        if (Objects.isNull(user)){
//            System.out.println("用户名或密码错误");
//            throw new RuntimeException("用户名或密码错误");
//        }
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        //如果认证通过则生成 jwt并把用户信息存入redis
        redisCache.setCacheObject("login:" + userId, loginUser);
        return new ResponseResult(200, "ok");
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        //删除redis的中用户信息
        redisCache.deleteObject("login:" + userId);
        return new ResponseResult(200, "ok");
    }
}
